﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;

using MM.Entities;
using MM.Business;  
namespace MM
{
    public partial class frmTaoPhieuXK : Form
    {
        string _matau = "";
        string _nguoitao = "";
        string _sConn = "";
        string _plant = "";
        List<TON_KHO> lstTonKho = new List<TON_KHO>();
        public List<VAT_TU_PHU_TUNG> lstVTPT = new List<VAT_TU_PHU_TUNG>();
        frmTimKiemVTPT frm;
        frmTimKiemTheoHinh frm1;
        frmImpa_TimKiem frm2;
        frmImpa_TimKiemTheoHinh frm3;

        public frmTaoPhieuXK(string sConn)
        {
            InitializeComponent();
            _sConn = sConn;

            _matau = frmDangNhap.objTau._tenTau2KiTu;
            _nguoitao = frmDangNhap.objTaiKhoan._soCMND;
           

            this.gridControl1.DataSource = lstTonKho;
            this.txtNgayThucHien.Text = DateTime.Today.Day.ToString() + "/" + DateTime.Today.Month.ToString() + "/" + DateTime.Today.Year.ToString();
            this.txtNguoiThucHien.Text = _nguoitao;

        }

        private void InitKho(string mavtpt)
        {
            clsKHO khoCtrl = new clsKHO(_sConn);
            List<KHO> lst = new List<KHO>();
            lst = khoCtrl.usp_SelectKHO_ByMaVTPT_TON_KHO(mavtpt);
            this.lookUpKho.Properties.DataSource = lst;
            this.lookUpKho.Properties.DisplayMember = "TenKho";
            this.lookUpKho.Properties.ValueMember = "MaKho";
        }

        private void InitTrangthai(string mavtpt, string makho)
        {
            clsTRANG_THAI_VTPT ttCtrl = new clsTRANG_THAI_VTPT(_sConn);
            List<TRANG_THAI_VTPT> lst = new List<TRANG_THAI_VTPT>();
            lst = ttCtrl.usp_SelectTRANG_THAI_VTPTByMaVTPT_TON_KHO(mavtpt, makho);
            this.lookUpTrangthai.Properties.DataSource = lst;
            this.lookUpTrangthai.Properties.DisplayMember = "TenTrangThai";
            this.lookUpTrangthai.Properties.ValueMember = "MaTrangThai";
            if (lst.Count > 0)
            {
                this.lookUpTrangthai.Properties.ForceInitialize();
                this.lookUpTrangthai.ItemIndex = 0;
            }
        }

       

        private void lookUpTrangthai_Closed(object sender, DevExpress.XtraEditors.Controls.ClosedEventArgs e)
        {
            try
            {
                string matrangthai = this.lookUpTrangthai.GetColumnValue("MaTrangThai").ToString();
                string makho = this.lookUpKho.GetColumnValue("MaKho").ToString();
                string mavtpt = this.txtMaVTPT.Text;
                if (makho != "" && matrangthai != "")
                {
                    this.txtSoLuong.Enabled = true;
                    clsTON_KHO tonCtrl = new clsTON_KHO(_sConn);
                    List<TON_KHO> lstton = new List<TON_KHO>();
                    lstton = tonCtrl.usp_SelectTON_KHO_ByMaKho(makho, mavtpt, int.Parse(matrangthai), null, null);
                    float soluongmax = 0;
                    for (int i = 0; i < lstton.Count; i++)
                    {
                        soluongmax += lstton[i].SoLuong;
                    }
                   

                    // kiem tra xem VTPT nay co cac phieu xuat kho nao chua duoc duyet
                    List<CHI_TIET_PXH> lstctpxh = new List<CHI_TIET_PXH>();
                    clsCHI_TIET_PXH ctpxhCtrl = new clsCHI_TIET_PXH(_sConn);
                    lstctpxh = ctpxhCtrl.usp_CheckSoLuongXuatKhoChuaDuyet(mavtpt, makho, int.Parse(matrangthai));
                    for (int i = 0; i < lstctpxh.Count; i++)
                    {
                        soluongmax -= lstctpxh[i].SoLuong;
                    }

                    // kiem tra xem VTPT nay da ton tai trong list can xuat kho chua
                    for (int i = 0; i < lstTonKho.Count; i++)
                    {
                        if (lstTonKho[i].MaVTPT == mavtpt && lstTonKho[i].MaKho == makho && lstTonKho[i].MaTrangThai == int.Parse(matrangthai))
                            soluongmax -= lstTonKho[i].SoLuong;
                    }

                    this.lblsoluongton.Text = soluongmax.ToString();
                }
                else
                {
                    this.txtSoLuong.Enabled = false;
                }
            }
            catch { }
        }

        private void cmdThemVTPT_Click(object sender, EventArgs e)
        {
           
            try
            {
                float soluongxuat = 0;
                float soluongton = 0;
                string matrangthai = this.lookUpTrangthai.GetColumnValue("MaTrangThai").ToString();
                string tentrangthai = this.lookUpTrangthai.GetColumnValue("TenTrangThai").ToString();
                string makho = this.lookUpKho.GetColumnValue("MaKho").ToString();
                string mavtpt = this.txtMaVTPT.Text;

                soluongxuat = float.Parse(this.txtSoLuong.Text.Trim());
                soluongton = float.Parse(this.lblsoluongton.Text);
                if (soluongxuat <= soluongton && matrangthai != "-1" && soluongxuat>0)
                {

                    TON_KHO tkObj = new TON_KHO();
                    tkObj.MaKho = makho;
                    tkObj.MaVTPT = mavtpt;
                    tkObj.TenVTPT = this.lblTenVTPT.Text.Trim();
                    tkObj.MaTrangThai = int.Parse(matrangthai);
                    tkObj.SoLuong = soluongxuat;
                    tkObj.MaGiaoTacKho = "XUATKHO";
                    tkObj.TenTrangThai = tentrangthai;

                    int k = lstTonKho.FindIndex(delegate(TON_KHO x) { return x.MaVTPT == mavtpt && x.MaTrangThai==tkObj.MaTrangThai && x.MaKho==tkObj.MaKho; });
                    if (k >= 0)
                    {
                        if (soluongxuat + lstTonKho[k].SoLuong <= soluongton)
                            lstTonKho[k].SoLuong += soluongxuat;
                        else
                            MessageBox.Show("KHÔNG THỂ THÊM VTPT" + mavtpt + "VÀO DS XUẤT KHO.\nTỔNG SỐ LƯỢNG XUẤT TRONG MỘT LẦN XUẤT CỦA MỘT VTPT PHẢI NHỎ HƠN HOẶC BẰNG SỐ LƯỢNG TỒN");
                    }
                    else
                    {
                        lstTonKho.Add(tkObj);

                        this.gridControl1.RefreshDataSource();

                        this.lookUpTrangthai.ItemIndex = 0;

                        if (lstVTPT.Count > 0)
                        {

                            lstVTPT.RemoveAt(0);

                            if (lstVTPT.Count > 0)
                            {
                                this.txtMaVTPT.Text = lstVTPT[0]._maVTPT;
                                this.lblTenVTPT.Text = lstVTPT[0]._tenVTPT;
                            }
                        }
                    }
                }
                else
                    this.txtSoLuong.Text = "0";
            }
            catch { }

        }

        private void cmdLuu_Click(object sender, EventArgs e)
        {
            PHIEU_XUAT_HANG oPXH = new PHIEU_XUAT_HANG();
            oPXH.NgayXuat = DateTime.Today;
            oPXH.NguoiXuat = _nguoitao;
            oPXH.PlantReferenceSAP = _plant;
            oPXH.MaTau = _matau;

            List<CHI_TIET_PXH> lstCTpxh = new List<CHI_TIET_PXH>();
            CHI_TIET_PXH oCT;
            for (int i = 0; i < lstTonKho.Count; i++)
            {
                oCT = new CHI_TIET_PXH();
                oCT.MaThietBi = lstTonKho[i].MaVTPT;
                oCT.SoLuong = lstTonKho[i].SoLuong;
                oCT.MaKho = lstTonKho[i].MaKho;
                oCT.MaTrangThai = lstTonKho[i].MaTrangThai;
                

                lstCTpxh.Add(oCT);
            }
            if (lstCTpxh.Count > 0)
            {
                clsPHIEU_XUAT_HANG pxhCtrl = new clsPHIEU_XUAT_HANG(_sConn);
                string maphieuxuathang = pxhCtrl.InsertPHIEU_XUAT_HANG(oPXH, lstCTpxh);
                if (maphieuxuathang != "")
                {
                    this.txtSoPhieuGI.Text = maphieuxuathang;
                    this.lstTonKho.Clear();
                }
                else
                    MessageBox.Show("LƯU DỮ LIỆU KHÔNG THÀNH CÔNG");
            }
        }

        private void gridDSVT_Click(object sender, EventArgs e)
        {
            GridView view = (GridView)sender;
            GridHitInfo info = view.CalcHitInfo(gridControl1.PointToClient(MousePosition));

            if (info.InRow || info.InRowCell)
            {
                float soluongmax = 0;

                this.txtMaVTPT.Text = lstTonKho[info.RowHandle].MaVTPT;
                this.lblTenVTPT.Text = lstTonKho[info.RowHandle].TenVTPT;
                this.txtSoLuong.Text = lstTonKho[info.RowHandle].SoLuong.ToString();

                this.InitKho(this.txtMaVTPT.Text);
                this.InitTrangthai(this.txtMaVTPT.Text, lstTonKho[info.RowHandle].MaKho);

                this.lookUpKho.ItemIndex= this.lookUpKho.Properties.GetDataSourceRowIndex("MaKho", lstTonKho[info.RowHandle].MaKho);
                this.lookUpTrangthai.ItemIndex = this.lookUpTrangthai.Properties.GetDataSourceRowIndex("MaTrangThai", lstTonKho[info.RowHandle].MaTrangThai);


                clsTON_KHO tonCtrl = new clsTON_KHO(_sConn);
                List<TON_KHO> lstton = new List<TON_KHO>();
                lstton = tonCtrl.usp_SelectTON_KHO_ByMaKho(lstTonKho[info.RowHandle].MaKho, lstTonKho[info.RowHandle].MaVTPT, lstTonKho[info.RowHandle].MaTrangThai, null, null);
                for (int i = 0; i < lstton.Count; i++)
                {
                    soluongmax += lstton[i].SoLuong;
                }
                   
                // kiem tra xem VTPT nay co cac phieu xuat kho nao chua duoc duyet
                List<CHI_TIET_PXH> lstctpxh = new List<CHI_TIET_PXH>();
                clsCHI_TIET_PXH ctpxhCtrl = new clsCHI_TIET_PXH(_sConn);
                lstctpxh = ctpxhCtrl.usp_CheckSoLuongXuatKhoChuaDuyet(lstTonKho[info.RowHandle].MaVTPT, lstTonKho[info.RowHandle].MaKho, lstTonKho[info.RowHandle].MaTrangThai);
                for (int i = 0; i < lstctpxh.Count; i++)
                {
                    soluongmax -= lstctpxh[i].SoLuong;
                }

                if (lstctpxh.Count > 0) // neu ton tai danh sach phieu xuat kho chua duyet thi hien thi link xem danh sach
                {
                    this.lnkPhieuChuaDuyet.Visible = true;                   
                }
                else
                    this.lnkPhieuChuaDuyet.Visible = false;

                // kiem tra xem VTPT nay da ton tai trong list can xuat kho chua
                for (int i = 0; i < lstTonKho.Count; i++)
                {
                    if (lstTonKho[i].MaVTPT == lstTonKho[info.RowHandle].MaVTPT && lstTonKho[i].MaKho == lstTonKho[info.RowHandle].MaKho && lstTonKho[i].MaTrangThai == lstTonKho[info.RowHandle].MaTrangThai)
                        soluongmax -= lstTonKho[i].SoLuong;
                }
                soluongmax += lstTonKho[info.RowHandle].SoLuong;

                this.lblsoluongton.Text = soluongmax.ToString();
            }
        }

        private void cmdCapNhatSL_Click(object sender, EventArgs e)
        {
            try
            {
                if (gridDSVT.FocusedRowHandle >= 0)
                {
                    int soluongxuat = int.Parse(this.txtSoLuong.Text.Trim());
                    int soluongton = int.Parse(this.lblsoluongton.Text);
                    string matrangthai = this.lookUpTrangthai.GetColumnValue("MaTrangThai").ToString();

                    if (soluongxuat <= soluongton && matrangthai != "-1" && lstTonKho[gridDSVT.FocusedRowHandle].MaVTPT==this.txtMaVTPT.Text)
                    {
                        lstTonKho[gridDSVT.FocusedRowHandle].SoLuong = int.Parse(this.txtSoLuong.Text);
                        lstTonKho[gridDSVT.FocusedRowHandle].MaKho = this.lookUpKho.GetColumnValue("MaKho").ToString();
                        lstTonKho[gridDSVT.FocusedRowHandle].MaTrangThai = int.Parse(this.lookUpTrangthai.GetColumnValue("MaTrangThai").ToString());

                        this.gridControl1.RefreshDataSource();
                    }

                }
                else
                    MessageBox.Show("Vui lòng chọn dòng có VTPT cần thay đổi thông tin ");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void cmdXoaVTPT_Click(object sender, EventArgs e)
        {
            try
            {
                if (gridDSVT.FocusedRowHandle >= 0)
                {
                    this.lstTonKho.RemoveAt(gridDSVT.FocusedRowHandle);
                    this.gridControl1.RefreshDataSource();                   
                }
                else
                    MessageBox.Show("Vui lòng chọn dòng có VTPT cần Xóa ");
            }
            catch { }
        }

        
        private void cmdTimVTPT_Click(object sender, EventArgs e)
        {
            //lstVTPT.Clear();
            //frm.SelectLstMaterial += new frmTimKiemVTPT.SelectListMaterialHandler(LuuDSVTPT);
            //frm.ShowDialog();
        }

        private void LuuDSVTPT(object sender, lstVtptEventArgs e)
        {
            lstVTPT = e.lstVtpt;
            if (lstVTPT.Count > 0)
            {
                this.txtMaVTPT.Text = lstVTPT[0]._maVTPT;
                this.lblTenVTPT.Text = lstVTPT[0]._tenVTPT;
            }
        }

        private void lookUpKho_QueryPopUp(object sender, CancelEventArgs e)
        {
            try
            {
                this.InitKho(this.txtMaVTPT.Text);
            }
            catch { }

        }

        private void lookUpTrangthai_QueryPopUp(object sender, CancelEventArgs e)
        {
            try
            {
                string makho = this.lookUpKho.GetColumnValue("MaKho").ToString();
                this.InitTrangthai(this.txtMaVTPT.Text, makho);
            }
            catch { }
        }

        private void tìmTheoNhiềuTiêuChíToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (frm == null)
            {
                frm = new frmTimKiemVTPT(_sConn,true);
                frm.SelectLstMaterial += new frmTimKiemVTPT.SelectListMaterialHandler(LuuDSVTPT);            
            }
            else
                lstVTPT.Clear();
            
            frm.ShowDialog();
            if (lstVTPT.Count > 0)
            {
                if (lstVTPT.Count > 1)
                {

                    MessageBox.Show("BẠN ĐANG CHỌN " + lstVTPT.Count.ToString() + " ĐỂ XUẤT KHO\nVUI LÒNG NHẬP THÔNG TIN CHO TỪNG VTPT ĐỂ XUẤT KHO");
                }
            }
        }

        private void tìmTheoHìnhToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (frm1 == null)
            {
                frm1 = new frmTimKiemTheoHinh(_sConn,true);
                frm1.SelectLstMaterialByImg += new frmTimKiemTheoHinh.SelectListMaterialByImgHandler(LuuDSVTPT);
            }
            else
                lstVTPT.Clear();
            frm1.ShowDialog();
            if (lstVTPT.Count > 0)
            {
                if (lstVTPT.Count > 1)
                {

                    MessageBox.Show("BẠN ĐANG CHỌN " + lstVTPT.Count.ToString() + " ĐỂ XUẤT KHO\nVUI LÒNG NHẬP THÔNG TIN CHO TỪNG VTPT ĐỂ XUẤT KHO");
                }
            }
        }

        private void frmTaoPhieuXK_Load(object sender, EventArgs e)
        {
            Common.SetColor(this);
        }

        private void lnkPhieuChuaDuyet_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                CHI_TIET_PXH oCTPXH = new CHI_TIET_PXH();
                oCTPXH.MaThietBi = lstTonKho[gridDSVT.FocusedRowHandle].MaVTPT;
                oCTPXH.MaKho = lstTonKho[gridDSVT.FocusedRowHandle].MaKho;
                oCTPXH.MaTrangThai = lstTonKho[gridDSVT.FocusedRowHandle].MaTrangThai;

                frmTimPhieuXK f = new frmTimPhieuXK(_sConn, oCTPXH, 0);
                f.chonPXK += new frmTimPhieuXK.ChonPhieuXuatKho(GetPhieuXuatKho);
                f.ShowDialog();
            }
            catch { }
        }
        private void GetPhieuXuatKho(object sender, ChonPhieuXKEventArgs e)
        {
            string mapxk = e.MaPhieuXuatKho;

            frmHienthiPhieuXK f = new frmHienthiPhieuXK(_sConn, mapxk);
            f.ShowDialog();
        }

        private void tìmVTIMPATheoNhiềuTiêuChíToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (frm2 == null)
            {
                frm2 = new frmImpa_TimKiem(_sConn,true);
                frm2.SelectLstMaterial += new frmImpa_TimKiem.SelectListMaterialHandler(LuuDSVTPT);
            }
            else
                lstVTPT.Clear();
            frm2.ShowDialog();
            if (lstVTPT.Count > 0)
            {
                if (lstVTPT.Count > 1)
                {

                    MessageBox.Show("BẠN ĐANG CHỌN " + lstVTPT.Count.ToString() + " ĐỂ XUẤT KHO\nVUI LÒNG NHẬP THÔNG TIN CHO TỪNG VTPT ĐỂ XUẤT KHO");
                }

            }
        }

        private void tìmVTIMPATheoHìnhToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (frm3 == null)
            {
                frm3 = new frmImpa_TimKiemTheoHinh(_sConn,true);
                frm3.SelectLstMaterial += new frmImpa_TimKiemTheoHinh.SelectListMaterialHandler(LuuDSVTPT);
            }
            else
                lstVTPT.Clear();
            frm3.ShowDialog();
            if (lstVTPT.Count > 0)
            {
                if (lstVTPT.Count > 1)
                {

                    MessageBox.Show("BẠN ĐANG CHỌN " + lstVTPT.Count.ToString() + " ĐỂ XUẤT KHO\nVUI LÒNG NHẬP THÔNG TIN CHO TỪNG VTPT ĐỂ XUẤT KHO");
                }

            }
        }

        private void txtMaVTPT_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                // kiểm tra tồn tại của VTPT                   

                VAT_TU_PHU_TUNG obj = new VAT_TU_PHU_TUNG();

                clsVAT_TU_PHU_TUNG vtptCtrl = new clsVAT_TU_PHU_TUNG(_sConn);

                obj = vtptCtrl.SelectVAT_TU_PHU_TUNG(this.txtMaVTPT.Text.Trim(), frmDangNhap.objTau.maTau);
                if (obj != null && obj._maVTPT != "" && obj._maVTPT != null)
                {
                    this.lblTenVTPT.Text = obj._tenVTPT;
                    this.cmdThemVTPT.Enabled = true;
                }
                else
                {
                    MessageBox.Show("KHÔNG TÌM THẤY THÔNG TIN VẬT TƯ NÀY");
                    this.cmdThemVTPT.Enabled = false;
                }
            }
        }
       
    }
}